// import OSREC from '@/libs/currencyFormatter.min.js'
import Decimal from '@/libs/decimal.min.js'

// 产品需求是：需要加,逗号，但是小数位不四舍五入，只是仅仅将多余的小数位截取掉

// 格式化千位符，currencyType参数可能未来要用到，因为有些货币格式不一样
let currency = (val = 0, currencyType = 'USD', symbol = '$', maxDecimal = 2) => {
  val = val || 0
  let numberSplit = val.toString().split('.')
  let integer = numberSplit[0]
  let decimal = numberSplit[1]
  let str = symbol + integer.replace(/\d(?=(?:\d{3})+\b)/g, '$&,') + (decimal ? '.' + decimal : '')

  typeof maxDecimal !== 'undefined' && (str = fillDecimal(str, maxDecimal))
  // OSREC.format(integer, { currency: currencyType, symbol: symbol }).replace(/\.\d+$/, decimal)
  return str
}

let formatThousands = (val = 0) => {
  val = val || 0
  let numberSplit = val.toString().split('.')
  let integer = numberSplit[0]
  let str = integer.replace(/\d(?=(?:\d{3})+\b)/g, '$&,')
  if (numberSplit.length > 1) {
    str = integer.replace(/\d(?=(?:\d{3})+\b)/g, '$&,') + '.' + numberSplit[1]
  }
  return str
}

// 限制小数位，补0
function fillDecimal (val = 0, maxDecimal = 2) {
  val = val || 0
  let numberSplit = val.toString().split('.')
  let integer = numberSplit[0]
  let decimal = numberSplit[1] || ''

  // 取有效小数位
  decimal = decimal.slice(0, maxDecimal) || ''

  // 若不够则补0
  let gap = maxDecimal - decimal.length
  gap && (decimal += (new Array(gap + 1).join(0)))

  return integer + (decimal ? '.' + decimal : '')
}

// 修复数值精度、科学记数法
let fixDecimal = (val = 0) => {
  return (new Decimal(val || 0)).toFixed(10)
}

// 限制小数位，但不补0
let limitDecimal = (val = 0, maxDecimal = 2) => {
  let numberSplit = val.toString().split('.')
  let integer = numberSplit[0]
  let decimal = numberSplit[1] || ''

  if (decimal) {
    decimal = '.' + decimal.slice(0, maxDecimal)
    val = decimal === '.' ? integer : integer + decimal
  }

  return val
}

// 限制小数位，去掉无效0
let trimDecimal = (val = 0, maxDecimal = 2) => {
  let numberSplit = val.toString().split('.')
  let integer = numberSplit[0]
  let decimal = numberSplit[1] || ''

  if (decimal) {
    decimal = '.' + decimal.slice(0, maxDecimal).replace(/0+$/, '')
    val = decimal === '.' ? integer : integer + decimal
  }

  return val
}

// 小数位必进1
let ceilDecimal = (val = 0, maxDecimal = 2) => {
  let tmp = Math.pow(10, maxDecimal)
  val = Math.ceil(val * tmp) / tmp
  return val
}

// 小数位四舍五入
let roundDecimal = (val = 0, maxDecimal = 2) => {
  let tmp = Math.pow(10, maxDecimal)
  val = Math.round(val * tmp) / tmp
  return val
}

export default {
  currency,
  formatThousands,
  limitDecimal,
  fillDecimal,
  fixDecimal,
  trimDecimal,
  ceilDecimal,
  roundDecimal
}
